var DxfParser = require('../');
var fs = require('fs');
var path = require('path');

var DXF_FILE_PATH = path.join(__dirname, 'data', 'tg.dxf');
var OUTPUT_FILE_NAME = "out.json";

var fileStream = fs.createReadStream(DXF_FILE_PATH, { encoding: 'utf8' });

var parser = new DxfParser();
var res_struct = {},max = {x:0,y:0},min = {}
//var layers = ['ASSIST','corrs','DXG','DLDW','TKDMTZ','GCD','GXYZ','ntk','SXSS','TK','wtk','ZBTZ']
var layers = ['0','7','Defpoints','DLSS','FWX','JMD','KZD','Store','Store_Mark','text','ZDH','ZJ','参考点','给水','给水内业点号','给水线注记','山西图廊']
var mis = ['gc002','GC170','GC200','gc146','gc086','1611341','1611381','1611121','1611411','GC013a',
'GC013B','GC013C','GC037','GC041','GC052','GC070','GC085','GC095','GC102','GC111','gc119',
'gc125','gc043','gc118','gc121','gc232','gc124','gc163','gc255','gc253',
'GC038','GC098','GC018',
  '47.00-00.00',
  'gc191',
  '47.00-95.00',
  'gc122',
  '47.00-96.00',
  'gc187',
  '47.00-97.00',
  'gc192',
  'GC017',
  '47.00-98.00',
  '41.00-95.00',
  'GC129A',
  'gc076',
  'GC181',
  'gc234',
  'GC183',
  '41.00-96.00',
  '42.00-95.00',
  '42.00-96.00',
  'GC133',
  'gc184',
  '43.00-95.00',
  '43.00-96.00',
  'GC097',
  'gc129',
  'gc096',
  'GC100',
  '44.00-95.00',
  'GC107',
  'gc132',
  '45.00-95.00',
  'GC108',
  '46.00-95.00',
  '46.00-96.00',
  'SHUITA',
  'YANCONG',
  'sdd'
]

parser.parseStream(fileStream, function(err, dxf) {
    if(err) return console.error(err.stack);
    //fs.writeFileSync(OUTPUT_FILE_NAME, JSON.stringify(dxf, null, 3));
    console.log(dxf.entities.length)
    dxf.entities = resetData(dxf)
    dxf.blocks = []
    var res = {}
    for(var key in res_struct){
        var len = res_struct[key].length
        //console.log(key,res_struct[key].length)
        if(!res[key]){
            res[key] = []
        }
        res[key].push(len)
        switch(key){
            //case 'LWPOLYLINE':
            case 'LINE':
            case 'POLYLINE':
            //if(res_struct[key].vertices)
                res_struct[key].map(function(e){
                    max.x = max.x < e.vertices[0].x ? e.vertices[0].x : max.x
                    max.y = max.y < e.vertices[0].y ? e.vertices[0].y : max.y
                    if(!min.x){
                        min.x = e.vertices[0].x
                        min.y = e.vertices[0].y
                    }
                    min.x = min.x > e.vertices[0].x ? e.vertices[0].x : min.x
                    min.y = min.y > e.vertices[0].y ? e.vertices[0].y : min.y
                })
                //console.log(res_struct[key][0])
                break;
        }
        console.log(key,len,res_struct[key].length)
    }
    console.log(max,min,dxf.entities.length)
    fs.writeFileSync(OUTPUT_FILE_NAME, JSON.stringify(dxf));
    console.log('Done writing output to ' + OUTPUT_FILE_NAME);
});
function getBlockEntity(dm,data,p){
    var res = [],po = {x:0,y:0,z:0}
    var en = dm
    switch(en.type){
        case 'DIMENSION':
            if(!en.view && en.position){
                en.view = en.position
            }
            console.log(en.block)
            // for(var i = 0;i < data.blocks[en.block].entities.length;i++){
            //     data.blocks[en.block].entities[i].view = en.view
            //     res = res.concat(getBlockEntity(data.blocks[en.block].entities[i],data))
            // }
            break;
        case 'INSERT':
            if(mis.indexOf(en.name) < 0){
                if(en.position){
                    po.x = en.position.x + p.x
                    po.y = en.position.y + p.y
                    po.z = en.position.z + p.z
                }
                else{
                    po = p
                }
                
                if(po.x > 6304296)
                console.log(en.name,po.x)
                for(var i = 0;i < data.blocks[en.name].entities.length;i++){
                    var temp = data.blocks[en.name].entities[i]
                    if(temp.flag){
                        temp.flag += 1
                    }
                    else{
                        temp.flag = 1
                    }
                    
                    res = res.concat(getBlockEntity(temp,data,po))
                }
            }
            break;
        default:
            if(!en.flag || (en.flag && en.flag == 1)){

           
            if(layers.indexOf(en.layer) >= 0){
                if(!res_struct[en.type]){
                    res_struct[en.type] = []
                }
              
                if(en.vertices){
                    if(en.vertices[0].x > 6304296)
                        console.log(en.layer,en.vertices[0].x)
                    en.vertices = en.vertices.map(function(e){
                        e.x += p.x
                        e.y += p.y
                        e.z += p.z
                        return e
                    })
                }
                else if(en.startPoint ){
                    en.startPoint.x += p.x
                    en.startPoint.y += p.y
                    en.startPoint.z += p.z
                }
                else if(en.position && en.type == "POINT"){
                    en.position.x += p.x
                    en.position.y += p.y
                    en.position.z += p.z
                }
                else if(en.center){
                    en.center.x += p.x
                    en.center.y += p.y
                    en.center.z += p.z
                }
                res_struct[en.type].push(en)
                res.push(en)
            }
        }
            break;
    }
    return res
}
function resetData(ob){
    var res = [],point = {x:0,y:0,z:0}
    ob.entities.map(function(e){
        res = res.concat(getBlockEntity(e,ob,point))
    })
    console.log(res.length)
    return res
}
//线段连接，将同层的线条连接在一起
    function check_dis(a,b){
        var flag = false;
        var dis = Math.sqrt(Math.pow(a.x - b.x,2) + Math.pow(a.y - b.y,2));
        
        if(dis == 0){
            flag =  true;
        }
        return flag;
    }
    function check_sam(a,b){
        var flag = true;
        if(a.length == b.length){
            a.map(function(e,i){
                if(!(e.x == b[i].x && e.y == b[i].y)){
                    flag = false
                }
            })
        }
        else{
            flag = false
        }
        return flag;
    }
    function array_contain(arr, obj){
        var num = 0,arr_e = arr.length - 1,obj_e = obj.length - 1;
        //console.log(arr, obj)
        if(check_dis(arr[arr_e],obj[0])){
            num = 1;
            if(check_sam(arr.reverse(), obj)){
                num = 5
            }
        }
        else if(check_dis(arr[arr_e],obj[obj_e])){
            num = 2;
            if(check_sam(arr, obj)){
                num = 5
            }
        }
        else if(check_dis(arr[0],obj[0])){
            num = 4;
            if(check_sam(arr, obj)){
                num = 5
            }
        }
        else if(check_dis(arr[0],obj[obj_e])){
            num = 3;
            if(check_sam(arr, obj.reverse())){
                num = 5
            }
        }
        return num;
    }
    function renderEntity(arr){
        var res = [],len = arr.length
        while(arr.length > 0){
            var result = [],enti = arr[0]
            console.log(arr.length,res.length)
            arr.map(function(en,index){
                if(index > 0){
                    if(enti.layer != en.layer){
                        result.push(en);
                    }
                    else{
                        switch(array_contain(enti.vertices,en.vertices)){
                            case 0:
                                result.push(en);
                                break;
                            case 1:
                                enti.vertices = enti.vertices.concat(en.vertices.filter(function(e,i){return i > 0;}));
                                break;
                            case 2:
                                enti.vertices = enti.vertices.concat(en.vertices.reverse().filter(function(e,i){return i > 0;}));
                                break;
                            case 3:
                                enti.vertices = en.vertices.concat(enti.vertices.filter(function(e,i){return i > 0;}));
                                break;
                            case 4:
                                enti.vertices = (en.vertices.reverse()).concat(enti.vertices.filter(function(e,i){return i > 0;}));
                                break;
                        }
                    }
                }
            })
            arr = result
            res.push(enti)
        }
        if(res.length == len ){
            return res
        }
        else{
            return renderEntity(res)
        }
        
    }